<template>
  <div class="article-list-container">
    <!-- 筛选条件 -->
    <el-card class="filter-card">
      <div class="filter-options">
        <div class="sort-options">
          <el-radio-group v-model="sortType" size="small" @change="handleFilterChange">
            <el-radio-button value="new">最新发布</el-radio-button>
            <el-radio-button value="hot">最多浏览</el-radio-button>
            <el-radio-button value="comment">最多评论</el-radio-button>
          </el-radio-group>
        </div>
        
        <div class="time-filter">
          <el-select v-model="timeRange" placeholder="时间范围" size="small" @change="handleFilterChange">
            <el-option label="全部时间" value="all"></el-option>
            <el-option label="最近一天" value="day"></el-option>
            <el-option label="最近一周" value="week"></el-option>
            <el-option label="最近一月" value="month"></el-option>
          </el-select>
        </div>
        
        <div class="search-box" v-if="!boardId">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索文章"
            prefix-icon="Search"
            clearable
            size="small"
            @keyup.enter="handleSearch"
          >
            <template #append>
              <el-button @click="handleSearch">搜索</el-button>
            </template>
          </el-input>
        </div>
      </div>
    </el-card>

    <!-- 板块信息 -->
    <div v-if="boardId && currentBoard" class="board-info">
      <el-card>
        <div class="board-header">
          <h2>{{ currentBoard.name }}</h2>
          <p class="board-description">{{ currentBoard.description }}</p>
          <div class="board-stats">
            <span class="stat-item">文章: {{ currentBoard.articleCount || 0 }}</span>
            <span class="stat-item">今日: +{{ currentBoard.todayCount || 0 }}</span>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 文章列表 -->
    <el-card class="article-list">
      <template #header>
        <div class="list-header">
          <h3>{{ pageTitle }}</h3>
          <el-button 
            type="primary" 
            size="small" 
            @click="$router.push('/article/create')" 
            v-if="isLoggedIn"
          >
            发布文章
          </el-button>
        </div>
      </template>
      
      <!-- 加载骨架屏 -->
      <div v-if="loading">
        <el-skeleton :rows="3" animated :count="5" />
      </div>
      
      <!-- 空状态 -->
      <el-empty
        v-else-if="articles.length === 0"
        description="暂无文章"
      ></el-empty>
      
      <!-- 文章列表内容 -->
      <div v-else>
        <div v-for="article in articles" :key="article.id" class="article-item">
          <div class="article-main">
            <!-- 文章内容 -->
            <div class="article-content">
              <div class="article-info">
                <span class="board-tag" v-if="!boardId">
                  <router-link :to="`/board/${article.boardId}`">
                    {{ getBoardName(article.boardId) }}
                  </router-link>
                </span>
                <router-link :to="`/user/${article.userId}`" class="user-link">
                  <el-avatar :size="24" :src="article.user && article.user.avatarUrl || defaultAvatar"></el-avatar>
                  <span>{{ article.user ? article.user.nickname : '未知用户' }}</span>
                </router-link>
                <span class="post-time">{{ formatDate(article.createTime) }}</span>
              </div>
              
              <router-link :to="`/article/${article.id}`" class="article-title">
                {{ article.title }}
                <span v-if="article.isTop" class="top-tag">置顶</span>
                <span v-if="article.isEssence" class="essence-tag">精华</span>
              </router-link>
              
              <p class="article-summary">{{ article.summary || (article.content ? article.content.substring(0, 100) + '...' : '') }}</p>
            </div>
          </div>
          
          <!-- 文章底部信息 -->
          <div class="article-footer">
            <div class="article-stats">
              <span class="stat-item">
                <el-icon><ViewIcon /></el-icon> {{ article.visitCount }}
              </span>
              <span class="stat-item">
                <el-icon><ChatDotRound /></el-icon> {{ article.replyCount }}
              </span>
              <span class="stat-item">
                <el-icon><Star /></el-icon> {{ article.likeCount }}
              </span>
            </div>
            
            <div class="article-tags" v-if="article.tags && article.tags.length > 0">
              <el-tag
                v-for="tag in article.tags.slice(0, 3)"
                :key="tag"
                size="small"
                type="info"
                effect="plain"
              >
                {{ tag }}
              </el-tag>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 分页 -->
      <div class="pagination-container" v-if="total > 0">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handlePageChange"
        ></el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
import { ref, computed, onMounted, watch } from 'vue'
import { useStore } from 'vuex'
import { useRoute, useRouter } from 'vue-router'
import { View as ViewIcon, ChatDotRound, Star } from '@element-plus/icons-vue'
import moment from 'moment'
import api from '@/api'
import { ElMessage } from 'element-plus'

export default {
  name: 'ArticleList',
  components: {
    ViewIcon,
    ChatDotRound,
    Star
  },
  setup() {
    const store = useStore()
    const route = useRoute()
    const router = useRouter()
    
    const loading = ref(true)
    const articles = ref([])
    const total = ref(0)
    const currentPage = ref(1)
    const pageSize = ref(10)
    const sortType = ref('new')
    const timeRange = ref('all')
    const searchKeyword = ref('')
    const defaultAvatar = require('@/assets/default-avatar.png')
    const currentBoard = ref(null)
    
    // 从路由参数获取板块ID
    const boardId = computed(() => route.params.id)
    
    // 页面标题
    const pageTitle = computed(() => {
      if (boardId.value && currentBoard.value) {
        return `${currentBoard.value.name} 板块文章`;
      } else if (route.query.q) {
        return `搜索：${route.query.q}`;
      } else {
        switch (sortType.value) {
          case 'hot': return '热门文章';
          case 'comment': return '热议文章';
          default: return '最新文章';
        }
      }
    })
    
    // 用户是否登录
    const isLoggedIn = computed(() => store.getters.isLoggedIn)
    
    // 获取板块名称
    const getBoardName = (id) => {
      const board = store.state.boards.find(b => b.id === id)
      return board ? board.name : '未知板块'
    }
    
    // 格式化日期
    const formatDate = (date) => {
      const momentDate = moment(date)
      const now = moment()
      
      if (now.diff(momentDate, 'hours') < 24) {
        return momentDate.fromNow()
      } else {
        return momentDate.format('YYYY-MM-DD')
      }
    }
    
    // 加载文章列表
    const loadArticles = async () => {
      loading.value = true
      
      try {
        // 设置默认参数
        const params = {
          page: currentPage.value || 1,
          size: pageSize.value || 10,
          sort: sortType.value || 'new',
          timeRange: timeRange.value || 'all'
        }
        
        // 如果是板块页面，添加板块ID
        if (boardId.value) {
          params.boardId = boardId.value
        }
        
        // 如果有搜索关键词，添加关键词
        if (route.query.q) {
          params.keyword = route.query.q
        } else if (searchKeyword.value) {
          params.keyword = searchKeyword.value
        }
        
        // 使用API服务发起请求
        const response = await api.article.getList(params)
        
        if (response && response.code === 0) {
          articles.value = response.data || []
          total.value = response.total || 0
        } else {
          ElMessage.error(response ? response.message : '加载文章列表失败')
        }
      } catch (error) {
        console.error('加载文章列表失败:', error)
        ElMessage.error('加载文章列表失败，请稍后重试')
      } finally {
        loading.value = false
      }
    }
    
    // 加载板块信息
    const loadBoardInfo = async () => {
      if (!boardId.value) return
      
      try {
        const response = await api.board.getBoardInfo(boardId.value)
        if (response.code === 0) {
          currentBoard.value = response.data
        }
      } catch (error) {
        console.error('加载板块信息失败', error)
      }
    }
    
    // 处理页码变化
    const handlePageChange = (page) => {
      currentPage.value = page
      loadArticles()
      
      // 滚动到顶部
      window.scrollTo({ top: 0, behavior: 'smooth' })
    }
    
    // 处理筛选条件变化
    const handleFilterChange = () => {
      currentPage.value = 1
      loadArticles()
    }
    
    // 处理搜索
    const handleSearch = () => {
      if (!searchKeyword.value.trim()) return
      
      router.push({
        path: '/articles',
        query: { q: searchKeyword.value.trim() }
      })
      
      currentPage.value = 1
      loadArticles()
    }
    
    // 初始化
    onMounted(() => {
      // 根据路由路径设置排序类型
      if (route.path === '/hot' || route.path === '/trending') {
        sortType.value = 'hot';
      } else if (route.path === '/new' || route.path === '/newest') {
        sortType.value = 'new';
      } else if (route.path === '/articles') {
        sortType.value = route.query.sort || 'new';
      }
      
      // 加载板块列表
      if (store.state.boards.length === 0) {
        store.dispatch('fetchBoards')
      }
      
      // 如果是板块页面，加载板块信息
      if (boardId.value) {
        loadBoardInfo()
      }
      
      // 如果路由有搜索参数，更新搜索关键词
      if (route.query.q) {
        searchKeyword.value = route.query.q
      }
      
      loadArticles()
    })
    
    // 监听路由变化
    watch(() => [route.path, route.params.id, route.query.q, route.query.sort], () => {
      currentPage.value = 1
      
      // 根据路由路径设置排序类型
      if (route.path === '/hot' || route.path === '/trending') {
        sortType.value = 'hot';
      } else if (route.path === '/new' || route.path === '/newest') {
        sortType.value = 'new';
      } else if (route.path === '/articles') {
        sortType.value = route.query.sort || 'new';
      }
      
      // 如果路由有搜索参数，更新搜索关键词
      if (route.query.q) {
        searchKeyword.value = route.query.q
      }
      
      // 如果是板块页面，加载板块信息
      if (boardId.value) {
        loadBoardInfo()
      }
      
      loadArticles()
    })
    
    return {
      loading,
      articles,
      total,
      currentPage,
      pageSize,
      sortType,
      timeRange,
      searchKeyword,
      boardId,
      currentBoard,
      pageTitle,
      isLoggedIn,
      defaultAvatar,
      getBoardName,
      formatDate,
      handlePageChange,
      handleFilterChange,
      handleSearch
    }
  }
}
</script>

<style scoped>
.article-list-container {
  padding: 0 15px;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-options {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  align-items: center;
}

.sort-options {
  flex-grow: 1;
}

.board-info {
  margin-bottom: 20px;
}

.board-header {
  text-align: center;
}

.board-header h2 {
  margin-top: 0;
  margin-bottom: 10px;
  color: #303133;
}

.board-description {
  color: #606266;
  margin-bottom: 15px;
}

.board-stats {
  display: flex;
  justify-content: center;
  gap: 20px;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.list-header h3 {
  margin: 0;
  color: #303133;
}

.article-item {
  padding: 20px 0;
  border-bottom: 1px solid #ebeef5;
}

.article-item:last-child {
  border-bottom: none;
}

.article-main {
  display: flex;
  gap: 20px;
}

.article-content {
  flex: 1;
}

.article-info {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 10px;
}

.board-tag {
  padding: 2px 8px;
  background-color: #f0f9eb;
  border-radius: 4px;
  font-size: 12px;
}

.board-tag a {
  color: #67c23a;
  text-decoration: none;
}

.user-link {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #606266;
  text-decoration: none;
}

.post-time {
  color: #909399;
  font-size: 13px;
}

.article-title:hover {
  color: #409EFF;
}

.top-tag, .essence-tag {
  display: inline-block;
  padding: 0 5px;
  margin-left: 8px;
  font-size: 12px;
  font-weight: normal;
  border-radius: 2px;
}

.top-tag {
  background-color: #f56c6c;
  color: white;
}

.essence-tag {
  background-color: #e6a23c;
  color: white;
}

.article-summary {
  color: #606266;
  font-size: 14px;
  line-height: 1.6;
  margin-bottom: 15px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.article-image {
  width: 180px;
  height: 120px;
  overflow: hidden;
  border-radius: 8px;
}

.article-image .el-image {
  width: 100%;
  height: 100%;
}

.article-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}

.article-stats {
  display: flex;
  gap: 15px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 14px;
  color: #909399;
}

.article-tags {
  display: flex;
  gap: 8px;
}

.pagination-container {
  margin-top: 30px;
  text-align: center;
}

@media (max-width: 768px) {
  .article-main {
    flex-direction: column;
  }
  
  .article-image {
    width: 100%;
    height: 180px;
    margin-top: 10px;
  }
  
  .filter-options {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .search-box {
    width: 100%;
  }
}
</style> 